<template>
  <a-card title="统计查询" :bordered="false" class="condition-card">
    <div class="condition-row">
      <div class="condition-col flex align-center justify-between">
        <div class="input-box flex align-center">
          <span class="label mr-20">选择网点</span>
          <a-select v-model:value="conditionState.wdCode" placeholder="请选择网点" allow-clear @change="handleShopChange">
            <a-select-option v-for="item in shopList" :value="item.wdCode" :key="item.id">{{item.wdname}}</a-select-option>
          </a-select>
        </div>
        <div class="input-box flex align-center ml-20">
          <span class="label mr-20">选择设备</span>
          <a-select v-model:value="conditionState.deviceId" placeholder="请选择设备" allow-clear>
            <a-select-option v-for="item in deviceList" :value="item.bianhao" :key="item.bianhao">{{item.name}}</a-select-option>
          </a-select>
        </div>
        <div class="input-box flex align-center ml-20">
          <span class="label mr-20">选择时段</span>
          <a-range-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model:value="conditionState.dateRange"/>
        </div>
        <a-button class="ml-20" type="primary" :loading="searchLoading" @click="handleSearch">查询</a-button>
      </div>
    </div>
  </a-card>
  <a-card title="统计结果" :bordered="false" class="result-card mt-20">
    <div class="charts-content">
      <div id="rechargeChart" class="charts"></div>
      <div id="consumeChart" class="charts"></div>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import * as echarts from "echarts";
import {formatDate} from "../../common/utils";
import merchantApi from "../../api/merchant";
import api from "../../api/statistics";
import deviceApi from "../../api/device";
import {DeviceItem, ResDto, ShopItem} from "../../types/common";

const today = new Date()
const prevDay = new Date(today.getTime()-7*24*60*60*1000)
const conditionState = reactive({
  dateRange: [formatDate(prevDay), formatDate(today)],
  deviceId: undefined,
  wdCode: undefined
})
const shopList = ref<ShopItem[]>([])
const getShopList = async () => {
  shopList.value = []
  try {
    const res = await merchantApi.getList({
      page: 0,
      size: 999,
    })
    if (res.content) {
      if (res.content.content && res.content.content.length) {
        shopList.value = res.content.content
      }
    }
  } catch (e: any) {
  }
}
getShopList()
const deviceList = ref<DeviceItem[]>([])
const getDeviceListByWdCode = async (wdCode: string) => {
  deviceList.value = []
  try {
    const res = await deviceApi.getListByWdCode(wdCode)
    if (res.content) {
      if (res.content && res.content.length) {
        deviceList.value = res.content
      }
    }
  } catch(e: any) {
  }
}
const handleShopChange = () => {
  conditionState.deviceId = undefined
  getDeviceListByWdCode(conditionState.wdCode)
}
let rechargeChart, consumeChart
const initChart = () => {
  rechargeChart = echarts.init(document.getElementById("rechargeChart"), "purple-passion");
  consumeChart = echarts.init(document.getElementById("consumeChart"), "purple-passion");
  // window.onresize = function () {
  //   chart.resize();
  // };
}
const setRechargeOptions = () => {
  rechargeChart.setOption({
    title: {
      text: "充值统计",
      left: 20,
    },
    grid: {
      top: '15%',
      left: 50,
      right: 50,
    },
    legend: {
      left: 'center',
      data: ['充值金额', '总充值数']
    },
    xAxis: {
      type: "category",
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        rotate: 45,
      },
      data: xData.value
    },
    tooltip: {
      trigger: "axis"
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        data: resultData.value.map((item: any) => item.amount),
        type: "line",
        name: '充值金额',
        smooth: true,
      },
      {
        data: resultData.value.map((item: any) => item.amountCount),
        type: "line",
        name: '总充值数',
        smooth: true,
      }
    ]
  });
}
const setConsumeOptions = () => {
  consumeChart.setOption({
    title: {
      text: "消费统计",
      left: 20,
    },
    grid: {
      top: '15%',
      left: 50,
      right: 50,
    },
    legend: {
      left: 'center',
      data: ['消费金额', '总消费数']
    },
    xAxis: {
      type: "category",
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        rotate: 45,
      },
      data: xData.value
    },
    tooltip: {
      trigger: "axis"
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        data: resultData.value.map((item: any) => item.consumerAmount),
        type: "line",
        name: '消费金额',
        smooth: false,
        lineGradient: false,
      },
      {
        data: resultData.value.map((item: any) => item.consumerCount),
        type: "line",
        name: '总消费数',
        smooth: false,
        lineGradient: false,
      }
    ]
  });
}
const searchLoading = ref(false)
const handleSearch = async () => {
  searchLoading.value = true
  try {
    resultData.value = []
    const res = await api.getStatisticsData({
      begin: conditionState.dateRange[0] || '',
      end: conditionState.dateRange[1] || '',
      deviceId: conditionState.deviceId || '',
      wdCode: conditionState.wdCode || '',
    })
    searchLoading.value = false
    if (res.content && res.content.length) {
      resultData.value = res.content
    }
  }catch(e){
    searchLoading.value = false
  }finally {
    xData.value = resultData.value.map((item: any) => item.date)
    setRechargeOptions()
    setConsumeOptions()
  }
}
const resultData = ref([])
const xData = ref([])
onMounted(() => {
  initChart()
  handleSearch()
})
</script>

<style scoped lang="less">
  .condition-col{
    .ant-select{
      min-width: 260px;
    }
    .ant-picker{
      min-width: 260px;
    }
  }
  .charts-content{
    position: relative;
    max-height: calc(100vh - 300px);
    .charts{
      position: relative;
      width: 100%;
      height: 500px;
      margin-top: 40px;
    }
  }
</style>
